﻿using System;
using System.Linq;
using System.Reflection;

namespace Furesoft.Addins.Internals.ScriptEngine
{
    public class ScriptEngineScope
    {
        public static void Resolve(JScriptEngine engine)
        {
            TypeResolver.Init(new[] { Assembly.GetEntryAssembly(), Assembly.GetCallingAssembly() });

            var types = TypeResolver.GetTypes();
            foreach (var t in types)
            {
                var ca = t.GetCustomAttributes(typeof(ScriptObjectAttribute), true);
                var cat = t.GetCustomAttributes(typeof(ScriptTypeAttribute), true);

                if (ca.Length == 1)
                {
                    foreach (var method in t.GetMethods())
                    {
                        engine.Add(method.Name, Delegate.CreateDelegate(t, method));
                    }
                    foreach (var prop in t.GetProperties())
                    {
                        engine.Add(prop.Name, prop.GetValue(Activator.CreateInstance(t), null));
                    }
                }
                if (cat.Length == 1)
                {
                    engine.Add(t.Name, t);
                }
            }
        }
    }
}